package com.ruoyi.common.utils.collection;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @Classname Lists
 * @Author: sunluquan
 * @Date: 2022/3/7 14:59
 * @Description TODO
 */
public class Lists {

    public static <E> ArrayList<E> newArrayList(E... elements) {
        // for GWT
        checkNotNull(elements);
        // Avoid integer overflow when a large array is passed in
        int capacity = computeArrayListCapacity(elements.length);
        ArrayList<E> list = new ArrayList<E>(capacity);
        Collections.addAll(list, elements);
        return list;
    }

    /**
     * 扩容至当前大小+当前大小的十分之一 +5
     * @param arraySize
     * @return
     */
    private static int computeArrayListCapacity(int arraySize) {
        checkNonnegative(arraySize, "arraySize");

        // TODO(kevinb): Figure out the right behavior, and document it
        return saturatedCast(5L + arraySize + (arraySize / 10));
    }

    /**
     *
     * @param value
     * @return
     */
    private static int saturatedCast(long value) {
        if (value > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (value < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        return (int) value;
    }
    /**
     *
     * @param value
     * @param name
     * @return
     */
    private static int checkNonnegative(int value, String name) {
        if (value < 0) {
            throw new IllegalArgumentException(name + " cannot be negative but was: " + value);
        }
        return value;
    }

    /**
     *
     * @param reference
     * @param <T>
     * @return
     */
    private static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw new NullPointerException();
        }
        return reference;
    }
}
